﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataAccess.SingleSignOn;
using Single_SignOn.Areas.Web.Models;
using Single_SignOn.Attributes;
using Single_SignOn.Json;
using Single_SignOn.Models;
using Single_SignOn.ResX;

namespace Single_SignOn.Areas.Web.Controllers
{
    public class AuthenticationController : Controller
    {
        public AuthenConnection oAuth;

        public UserProfile _userProfile;
        //
        // GET: /PC/oAuthentication/
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index()
        {
            if (Request.QueryString["token"] == null)
            {
                if (WebConfig.ActiveDirectiry)
                {
                    ActiveDirectiry();
                    if (Session["UserInfo"] != null)
                        return RedirectToAction("Index"
                            , "ApplicationList"
                            , (UserProfile) _userProfile
                            );
                    else
                        return View("Index");
                }
                else
                    return View("Index");
            }
            else
            {
                string token = (string) Request.QueryString["token"];
                oAuth = new AuthenConnection();
                // Get Token
                DataTable dtToken = oAuth.getAppTokenData(token);
                if (dtToken != null)
                    if (dtToken.Rows.Count > 0)
                    {
                        ActiveDirectiry(Convert.ToString(dtToken.Rows[0]["EMPNO"]));
                        if (Session["UserInfo"] != null)
                        {
                            // Deleted Token
                            oAuth.DeleteToken(Convert.ToInt32(dtToken.Rows[0]["APPTOKEN"]));
                            // Return Application Lists
                            return RedirectToAction("Index"
                                , "ApplicationList"
                                , (UserProfile) _userProfile
                                );
                        }
                    }

                return View("Index");
            }
            
        }

        [JsonFilterAttribute(Param = "oAuthenticationDataObj", RootType = typeof(oAuthenticationDataContract))]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(oAuthenticationDataContract oAuthenticationDataObj)
        {
            // for get Active Directiry Default
            // Checked
            if (!WebConfig.ActiveDirectiry)
                // Single SignOn
                if ((((oAuthenticationDataContract)oAuthenticationDataObj).RadioLogin).Equals("SSL"))
                {
                    return Json(new { redirectToUrl = Url.Action("Index", "Login", 0, "http") });
                }
                // AD
                else
                {
                    ActiveDirectiry();

                    if (Session["UserInfo"] != null)
                        return Json(new { redirectToUrl = Url.Action("Index", "ApplicationList") });
                    else
                        return Json(new { redirectToUrl = Url.Action("Index") });
                }

            return Json(new { redirectToUrl = Url.Action("Index") });
        }

        [Authorize]
        private void ActiveDirectiry(String ActiveName = null)
        {
            string ADUserName = (string)((ActiveName == null) ? (String)(System.Web.HttpContext.Current.User.Identity.Name) : ActiveName);

            //ADUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString().Trim();

            if (ADUserName != string.Empty)
            {
                ADUserName = HttpUtility.UrlEncode(ADUserName);
                ADUserName = ADUserName.Replace("%5c", "").ToLower();

               // Response.Write(ADUserName);

                if (!string.IsNullOrEmpty(ADUserName))
                {

                    DataAccess.SingleSignOn.AuthenConnection oAuth = new DataAccess.SingleSignOn.AuthenConnection();
                    DataTable dtUserData = oAuth.getUserData(ADUserName);

                    if (dtUserData != null)
                        if (dtUserData.Rows.Count > 0)
                        {
                            // Remove Session UserInfo
                            Session.Remove("UserInfo");
                            _userProfile = new UserProfile();
                            _userProfile.Description = (System.DBNull.Value == dtUserData.Rows[0]["DESCRIPTION"]) ? "" : (string)dtUserData.Rows[0]["DESCRIPTION"];
                            _userProfile.GroupDescription = (System.DBNull.Value == dtUserData.Rows[0]["GROUPDESC"]) ? "" : (string)dtUserData.Rows[0]["GROUPDESC"];
                            _userProfile.EmployeeNo = (System.DBNull.Value == dtUserData.Rows[0]["EMPID"]) ? "" : (string)dtUserData.Rows[0]["EMPID"];
                            _userProfile.Username = (System.DBNull.Value == dtUserData.Rows[0]["EMPNO"]) ? "" : (string)dtUserData.Rows[0]["EMPNO"];
                            _userProfile.FullName = (System.DBNull.Value == dtUserData.Rows[0]["EMPNAME"]) ? "" : (string)dtUserData.Rows[0]["EMPNAME"];
                            _userProfile.Password = (System.DBNull.Value == dtUserData.Rows[0]["PASSWORD"]) ? "" : (string)dtUserData.Rows[0]["PASSWORD"];
                            _userProfile.GroupNo = (System.DBNull.Value == dtUserData.Rows[0]["GROUPNO"]) ? "" : (string)dtUserData.Rows[0]["GROUPNO"];
                            _userProfile.Division = (System.DBNull.Value == dtUserData.Rows[0]["DIVISION"]) ? "" : (string)dtUserData.Rows[0]["DIVISION"];
                            _userProfile.Store = (System.DBNull.Value == dtUserData.Rows[0]["STORENO"]) ? "" : (string)dtUserData.Rows[0]["STORENO"];
                            _userProfile.Tel = (System.DBNull.Value == dtUserData.Rows[0]["TEL"]) ? "" : (string)dtUserData.Rows[0]["TEL"];
                            _userProfile.Email = (System.DBNull.Value == dtUserData.Rows[0]["EMAIL"]) ? "" : (string)dtUserData.Rows[0]["EMAIL"];
                            _userProfile.Status = (System.DBNull.Value == dtUserData.Rows[0]["STATUS"]) ? "" : (string)dtUserData.Rows[0]["STATUS"];
                            _userProfile.ApplNo = (System.DBNull.Value == dtUserData.Rows[0]["APPLNO"]) ? "" : (string)dtUserData.Rows[0]["APPLNO"];
                            _userProfile.ProfileLevel = (System.DBNull.Value == dtUserData.Rows[0]["PROFILELEVEL"]) ? "" : (string)dtUserData.Rows[0]["PROFILELEVEL"];
                            _userProfile.Language = (System.DBNull.Value == dtUserData.Rows[0]["LANG"]) ? "" : (string)dtUserData.Rows[0]["LANG"];
                            // Set Session UserInfo
                            Session["UserInfo"] = _userProfile;
                        }
                        // Default Session UserInfo
                        else
                            Session["UserInfo"] = null;
                    else
                        Session["UserInfo"] = null;
                }

            }
        }
    }
}
